package com.aiwhose.aiwhosewechatplublicaiwhose.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aiwhose.aiwhosecore.bean.plublicaiwhose.xunfei.BigModelRequest;
import com.aiwhose.aiwhosewechatplublicaiwhose.utils.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class XunFeiBigModelService {

    private static final Logger log = LoggerFactory.getLogger(XunFeiBigModelService.class);
    @Value("${bigmodel.apiKey}")
    private String apiKey;

    @Value("${bigmodel.apiSecret}")
    private String apiSecret;

    @Value("${bigmodel.hostUrl}")
    private String hostUrl;

    @Resource
    RedisUtil redisUtil;

    private final OkHttpClient client = new OkHttpClient();
    private final ObjectMapper objectMapper = new ObjectMapper();

    public String getAnswer(String userId, String question) throws IOException {
        // 构建请求体对象
        long messaheSize = redisUtil.lGetListSize("XUNFEI:MESSAHE:HISTORY:" + userId);
        long startIndex = 0;
        long endIndex = 0;
        if (messaheSize > 40) {
            startIndex = messaheSize - 40;
            endIndex = messaheSize;
        } else {
            startIndex = 0;
            endIndex = messaheSize;
        }
        List<Object> historyObject = redisUtil.lGet("XUNFEI:MESSAHE:HISTORY:" + userId, startIndex, endIndex);
        // 将历史问题转换为 BigModelRequest.Message 对象列表
        List<BigModelRequest.Message> messages = new ArrayList<>();
        if (historyObject != null) {
            for (Object history : historyObject) {
                messages.add(new BigModelRequest.Message("user", StrUtil.toString(history)));
            }
        }

        BigModelRequest.Message userMessage = new BigModelRequest.Message("user", question);
        redisUtil.rSet("XUNFEI:MESSAHE:HISTORY:" + userId, userMessage, 60 * 60 * 24);
        // 添加当前问题到消息列表中
        messages.add(new BigModelRequest.Message("user", question));

        // 构建请求体
        BigModelRequest requestBody = new BigModelRequest();
        requestBody.setModel("general");
        requestBody.setMessages(messages);

        // 序列化请求体为 JSON
        String json = objectMapper.writeValueAsString(requestBody);

        // 构建请求
        Request request = new Request.Builder()
                .url(hostUrl)
                .post(RequestBody.create(json, MediaType.get("application/json; charset=utf-8")))
                .addHeader("Authorization", "Bearer " + apiKey + ":" + apiSecret)
                .addHeader("Content-Type", "application/json")
                .build();

        // 发起请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            String body = response.body().string();

            log.error(body);
            JSONObject entries = JSONUtil.parseObj(body);
            if (entries.getInt("code") == 0) {
                JSONArray choices = entries.getJSONArray("choices");
                JSONObject message = choices.getJSONObject(choices.size() - 1);
                JSONObject message1 = message.getJSONObject("message");
                String content = message1.getStr("content");

                // 将当前问题和响应结果存入 Redis 历史记录
                BigModelRequest.Message assistant = new BigModelRequest.Message("assistant", content);
                redisUtil.rSet("XUNFEI:MESSAHE:HISTORY:" + userId, assistant, 60 * 60 * 24);
                return content;

            }
            return "系统错误,未能获取到数据，请微信联系： aiwhose ";

        } catch (Exception e) {
            return "系统错误，请微信联系： aiwhose ";
        }
    }

}
